package com.fangrui.aop;

import com.alibaba.fastjson.JSONObject;
import com.fangrui.mapper.OperateLogMapper;
import com.fangrui.pojo.OperateLog;
import com.fangrui.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

//Created by ✎﹏ℳ๓独赏☆独醉 on 2025/5/5 10:25
@Slf4j
@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.fangrui.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
//        1、获取操作人的id
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer id = (Integer) claims.get("id");
//        2、记录操作时间
        LocalDateTime now = LocalDateTime.now();
//        3、操作类名
        String className = joinPoint.getTarget().getClass().getName();
//        4、操作方法名
        String methodName = joinPoint.getSignature().getName();
//        5、操作方法参数
        Object[] args = joinPoint.getArgs();
        long start = System.currentTimeMillis();
//        6、方法返回值
        Object res = joinPoint.proceed();
        long end = System.currentTimeMillis();
//        7、执行耗时
        long time = end - start;
        OperateLog operateLog = new OperateLog(null,id,now,className,methodName, Arrays.toString(args), JSONObject.toJSONString(res),time);
        operateLogMapper.insert(operateLog);
        log.info(JSONObject.toJSONString(operateLog));
        return res;
    }
}
